<?php

namespace app\model;

use app\common\controller\PreciseCalculator;
use think\Exception;
use think\facade\Db;

class OrderModel extends BaseModel
{
    protected $name = 'dingdan';


    public const TYPE_DZ = 100; //定制产品
    public const TYPE_BZ = 200; //标准产品

    public const STATUS_WAIT = 100; //待发起审批
    public const STATUS_ING = 200; //审批中
    public const STATUS_FAIL = 300; //被驳回
    public const STATUS_SUCCESS = 400; //成功
    public const STATUS_WAITING_MATERIAL = 500; //待领料

    public const STATUS_OUTSOURCING_TO_BE_CONFIRMED = 501; // Outsourcing to be confirmed
    public const STATUS_MATERIAL_RECEIVED_IN_PRODUCTION = 600; //已领料生产中
    public const STATUS_PRODUCTION_COMPLETED = 700; //生产完成
    public const STATUS_WAREHOUSED = 800; //入库
    public const STATUS_DELIVERY_CONFIRMED = 1000; //确认交付

    public const STATUS_OUTSOURCING_IN_PRODUCTION = 1100; //外协生产中
    public const STATUS_OUTSOURCING_COMPLETED = 1200; //外协生产完成

    public const STATUS_LIST = [
        [
            'status' => self::STATUS_WAIT,
            'name' => '待发起审批'
        ],
        [
            'status' => self::STATUS_ING,
            'name' => '审批中'
        ],
        [
            'status' => self::STATUS_FAIL,
            'name' => '被驳回'
        ],
        [
            'status' => self::STATUS_SUCCESS,
            'name' => '成功'
        ],
        [
            'status' => self::STATUS_WAITING_MATERIAL,
            'name' => '待领料'
        ],
        [
            'status' => self::STATUS_MATERIAL_RECEIVED_IN_PRODUCTION,
            'name' => '已领料生产中'
        ],
        [
            'status' => self::STATUS_PRODUCTION_COMPLETED,
            'name' => '生产完成'
        ],
        [
            'status' => self::STATUS_WAREHOUSED,
            'name' => '入库'
        ],
        [
            'status' => self::STATUS_DELIVERY_CONFIRMED,
            'name' => '确认交付'
        ],
        [
            'status' => self::STATUS_OUTSOURCING_IN_PRODUCTION,
            'name' => '外协生产中'
        ],
        [
            'status' => self::STATUS_OUTSOURCING_COMPLETED,
            'name' => '外协生产完成'
        ],
    ];


    /**
     * Notes: 仓库的列表
     * User: chenLei
     * Date: 10/26/25 15:25:04
     * @param $params
     * @return array
     */
    public function list($params): array
    {
        $where = [];

        $user = getUserInfo();
        $dataRole = dataPermissionCheck($user);
        if (in_array($dataRole, ['user', 'company'])) {
            $where[] = ['o.company_id', '=', $user['company_id']];
        }

        if (!empty($params['dingdan_code'])) {
            $where[] = ['o.dingdan_code', '=', $params['dingdan_code']];
        }

        if (!empty($params['dingdan_status'])) {
            $where[] = ['o.dingdan_status', '=', $params['dingdan_status']];
        }


        //  $where[] = ['vendors_id', '=', 0];
        $where[] = ['o.dingdan_status', 'in', [self::STATUS_WAITING_MATERIAL, self::STATUS_MATERIAL_RECEIVED_IN_PRODUCTION,
            self::STATUS_PRODUCTION_COMPLETED, self::STATUS_WAREHOUSED, self::STATUS_DELIVERY_CONFIRMED]];

        $list = $this->alias('o')->leftJoin('customer c', 'c.id = o.customer_id')
            ->leftJoin('user u', 'u.id = o.user_id')
            ->where($where)
            ->field('o.*,c.customer_name,u.realname,c.phone1')->order('o.id desc')
            ->paginate($params['page_size'] ?? 15)->toArray();


        return $list;
    }

    /**
     * Notes: 订单列表 （生产部门）
     * User: chenLei
     * Date: 10/27/25 11:14:14
     * @param $params
     * @return mixed
     */
    public function productionList($params)
    {
        $where = [];

        $user = getUserInfo();
        $dataRole = dataPermissionCheck($user);
        if (in_array($dataRole, ['user', 'company'])) {
            $where[] = ['o.company_id', '=', $user['company_id']];
        }

        if (!empty($params['dingdan_code'])) {
            $where[] = ['o.dingdan_code', '=', $params['dingdan_code']];
        }

        if (!empty($params['dingdan_status'])) {
            $where[] = ['o.dingdan_status', '=', $params['dingdan_status']];
        }

        //  $where[] = ['vendors_id', '=', 0];
        $where[] = ['o.dingdan_status', 'in', [self::STATUS_WAITING_MATERIAL, self::STATUS_MATERIAL_RECEIVED_IN_PRODUCTION,
            self::STATUS_PRODUCTION_COMPLETED, self::STATUS_WAREHOUSED, self::STATUS_DELIVERY_CONFIRMED]];

        $list = $this->alias('o')->leftJoin('customer c', 'c.id = o.customer_id')
            ->leftJoin('user u', 'u.id = o.user_id')
            ->where($where)
            ->field('o.*,c.customer_name,u.realname,c.phone1')->order('o.id desc')
            ->paginate($params['page_size'] ?? 15)->toArray();


        return $list;
    }

    /**
     * Notes: 添加销售订单
     * User: chenLei
     * Date: 9/9/25
     * @param $params
     * @return bool
     */
    public function add($params)
    {

        if ($this->where('dingdan_code', $params['dingdan_code'])->count()) {
            $this->error = '重复的订单号';
            return false;
        }


        if ($params['product_type'] == self::TYPE_DZ) {

            if (empty($params['bom']) || count($params['bom']) <= 0) {
                $this->error = '请添加bom清单';
                return false;
            }

            $bom = [];
            $order_price = 0;
            $cost_amount = 0;
            foreach ($params['bom'] as $item) {
                $material = MaterialCategoryModel::where('id', $item['material_id'])->findOrEmpty();
                if ($material->isEmpty()) {
                    $this->error = '不存在的物料，请重新选择bom清单';
                    return false;
                }
                $sum_price = PreciseCalculator::mul($item['price'], $item['material_quantity']);
                $sum_cost_price = PreciseCalculator::mul($material['cost_price'], $item['material_quantity']);
                $profit_price = PreciseCalculator::sub($sum_price, $sum_cost_price);

                $cost_amount = PreciseCalculator::add($cost_amount, $sum_cost_price);
                $order_price = PreciseCalculator::add($order_price, $sum_price);
                $bom[] = [
                    'material_id' => $material['id'],
                    'material_name' => $material['material_name'],
                    'material_quantity' => $item['material_quantity'],
                    'price' => $item['price'],
                    'sum_price' => $sum_price,
                    'cost_price' => $material['cost_price'],
                    'sum_cost_price' => $sum_cost_price,
                    'profit_price' => $profit_price,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
            }


            if (count($bom) <= 0) {
                $this->error = '请添加bom清单';
                return false;
            }

            Db::startTrans();
            try {

                $this->save([
                    'company_id' => $params['company_id'],
                    'user_id' => $params['login_user_id'] ?? 0,
                    'vendors_id' => $params['vendors_id'] ?? 0,
                    'line_id' => $params['line_id'] ?? 0,
                    'dingdan_code' => $params['dingdan_code'],
                    'dingdan_date' => $params['dingdan_date'],
                    'product_type' => $params['product_type'],
                    'product_id' => $params['product_id'] ?? 0,
                    'product_name' => $params['product_name'],
                    'customer_id' => $params['customer_id'],
                    'delivery_date' => $params['delivery_date'],
                    'technical_requirements' => $params['technical_requirements'] ?? '',
                    'design_drawings' => $params['design_drawings'] ?? '',
                    'remarks' => $params['remarks'] ?? '',
                    'price' => $order_price,
                    'amount' => $order_price,
                    'cost_amount' => $cost_amount,
                    'profit_amount' => PreciseCalculator::sub($order_price, $cost_amount),
                    'dingdan_status' => self::STATUS_WAIT,
                ]);

                foreach ($bom as &$item) {
                    $item['dingdan_id'] = $this->id;
                }

                OrderBomModel::insertAll($bom);

                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error = $exception->getMessage();
                return false;
            }

        } else if ($params['product_type'] == self::TYPE_BZ) {

            if (empty($params['product']) || count($params['product']) <= 0) {
                $this->error = '请选择产品';
                return false;
            }

            $productOrder = [];
            $order_price = 0;
            $cost_amount = 0;
            foreach ($params['product'] as $item) {
                $product = ProductModel::where('id', $item['product_id'])->findOrEmpty();
                if (empty($product)) {
                    $this->error = '产品不存在';
                    return false;
                }

                $sum_price = PreciseCalculator::mul($item['price'], $item['product_quantity']);  //单价*数量
                $sum_cost_price = PreciseCalculator::mul($product['cost_price'], $item['product_quantity']);//成本价*数量
                $profit_price = PreciseCalculator::sub($sum_price, $sum_cost_price); //利润

                $order_price = PreciseCalculator::add($order_price, $sum_price); //订单总价
                $cost_amount = PreciseCalculator::add($cost_amount, $sum_cost_price);// 成本总价

                $bomList = ProductBomModel::where('product_id', $item['product_id'])->select();

                $bom = [];
                foreach ($bomList as $bomListItem) {

                    $material = MaterialCategoryModel::where('id', $bomListItem['material_id'])->findOrEmpty();
                    if ($material->isEmpty()) {
                        $this->error = '不存在的物料，请重新选择bom清单';
                        return false;
                    }
                    $material_quantity = $bomListItem['quantity'] * $item['product_quantity'];
                    $material_sum_price = PreciseCalculator::mul($material['cost_price'], $material_quantity);

                    $bom[] = [
                        'material_id' => $material['id'],
                        'material_name' => $material['material_name'],
                        'difference' => $material['spec'],
                        'material_quantity' => $material_quantity,
                        'price' => $material['cost_price'],
                        'sum_price' => $material_sum_price,
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                }

                $productOrder[] = [

                    'product_id' => $item['product_id'],
                    'product_name' => $product['product_name'],
                    'product_code' => $product['product_code'],
                    'product_quantity' => $item['product_quantity'],
                    'price' => $item['price'],
                    'sum_price' => $sum_price,
                    'cost_price' => $product['cost_price'],
                    'sum_cost_price' => $sum_cost_price,
                    'profit_price' => $profit_price,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                    'bom' => $bom
                ];

            }


            Db::startTrans();
            try {

                $this->save([
                    'company_id' => $params['company_id'],
                    'user_id' => $params['login_user_id'] ?? 0,
                    'vendors_id' => $params['vendors_id'] ?? 0,
                    'line_id' => $params['line_id'] ?? 0,
                    'dingdan_code' => $params['dingdan_code'],
                    'dingdan_date' => $params['dingdan_date'],
                    'product_type' => $params['product_type'],
                    'customer_id' => $params['customer_id'],
                    'delivery_date' => $params['delivery_date'],
                    'technical_requirements' => $params['technical_requirements'] ?? '',
                    'design_drawings' => $params['design_drawings'] ?? '',
                    'remarks' => $params['remarks'] ?? '',
                    'price' => $order_price,
                    'amount' => $order_price,
                    'cost_amount' => $cost_amount,
                    'profit_amount' => PreciseCalculator::sub($order_price, $cost_amount),
                    'dingdan_status' => self::STATUS_WAIT,
                ]);

                foreach ($productOrder as $productItem) {
                    $productItem['dingdan_id'] = $this->id;
                    $bom = $productItem['bom'];
                    unset($productItem['bom']);
                    $dingdan_product_id = OrderProductModel::insertGetId($productItem);
                    foreach ($bom as $bomItem) {
                        $bomItem['dingdan_id'] = $this->id;
                        $bomItem['dingdan_product_id'] = $dingdan_product_id;
                        OrderBomModel::insert($bomItem);
                    }

                }


                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->error = $exception->getMessage();
                return false;
            }
        }


        return true;

    }


    /**
     * Notes: 编辑订单
     * User: chenLei
     * Date: 9/9/25
     * @param $params
     * @return bool
     */
    public function edit($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if ($info->dingdan_status != self::STATUS_WAIT && $info->dingdan_status != self::STATUS_FAIL) {
            $this->error = '该订单状态不支持编辑修改';
            return false;
        }

        if ($params['product_type'] == self::TYPE_DZ) {

            $bom = [];
            $order_price = 0;
            foreach ($params['bom'] as $item) {
                $material = MaterialCategoryModel::where('id', $item['material_id'])->findOrEmpty();
                if ($material->isEmpty()) {
                    $this->error = '不存在的物料，请重新选择bom清单';
                    return false;
                }
                $sum_price = PreciseCalculator::mul($item['price'], $item['material_quantity']);
                $order_price = PreciseCalculator::add($order_price, $sum_price);
                $bom[] = [
                    'material_id' => $material['id'],
                    'material_name' => $material['material_name'],
                    'material_quantity' => $item['material_quantity'],
                    'price' => $item['price'],
                    'sum_price' => $sum_price,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
            }
            if (count($bom) <= 0) {
                $this->error = '请添加bom清单';
                return false;
            }
            $order_amount = PreciseCalculator::mul($order_price, $params['quantity']);

            Db::startTrans();
            try {

                $info->save([
                    'vendors_id' => $params['vendors_id'] ?? 0,
                    'line_id' => $params['line_id'] ?? 0,
                    'dingdan_code' => $params['dingdan_code'],
                    'dingdan_date' => $params['dingdan_date'],
                    'product_type' => $params['product_type'],
                    'product_id' => $params['product_id'] ?? 0,
                    'customer_id' => $params['customer_id'],
                    'quantity' => $params['quantity'] ?? 1,
                    'delivery_date' => $params['delivery_date'],
                    'technical_requirements' => $params['technical_requirements'] ?? '',
                    'design_drawings' => $params['design_drawings'] ?? '',
                    'remarks' => $params['remarks'] ?? '',
                    'price' => $order_price,
                    'amount' => $order_amount,
                    'dingdan_status' => self::STATUS_WAIT,
                ]);

                foreach ($bom as &$item) {
                    $item['dingdan_id'] = $info['id'];
                }
                OrderBomModel::where('dingdan_id', $info['id'])->delete();
                OrderBomModel::insertAll($bom);

                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error = $exception->getMessage();
                return false;
            }

        } else if ($params['product_type'] == self::TYPE_BZ) {

            if (empty($params['product']) || count($params['product']) <= 0) {
                $this->error = '请选择产品';
                return false;
            }

            $productOrder = [];
            $order_price = 0;
            $cost_amount = 0;
            foreach ($params['product'] as $item) {
                $product = ProductModel::where('id', $item['product_id'])->findOrEmpty();
                if (empty($product)) {
                    $this->error = '产品不存在';
                    return false;
                }

                $sum_price = PreciseCalculator::mul($item['price'], $item['product_quantity']);  //单价*数量
                $sum_cost_price = PreciseCalculator::mul($product['cost_price'], $item['product_quantity']);//成本价*数量
                $profit_price = PreciseCalculator::sub($sum_price, $sum_cost_price); //利润

                $order_price = PreciseCalculator::add($order_price, $sum_price); //订单总价
                $cost_amount = PreciseCalculator::add($cost_amount, $sum_cost_price);// 成本总价

                $bomList = ProductBomModel::where('product_id', $item['product_id'])->select();

                $bom = [];
                foreach ($bomList as $bomListItem) {

                    $material = MaterialCategoryModel::where('id', $bomListItem['material_id'])->findOrEmpty();
                    if ($material->isEmpty()) {
                        $this->error = '不存在的物料，请重新选择bom清单';
                        return false;
                    }
                    $material_quantity = $bomListItem['quantity'] * $item['product_quantity'];
                    $material_sum_price = PreciseCalculator::mul($material['cost_price'], $material_quantity);
                    $bom[] = [
                        'material_id' => $material['id'],
                        'material_name' => $material['material_name'],
                        'difference' => $material['spec'],
                        'material_quantity' => $material_quantity,
                        'price' => $material['cost_price'],
                        'sum_price' => $material_sum_price,
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                }

                $productOrder[] = [
                    'product_id' => $item['product_id'],
                    'product_name' => $product['product_name'],
                    'product_code' => $product['product_code'],
                    'product_quantity' => $item['product_quantity'],
                    'price' => $item['price'],
                    'sum_price' => $sum_price,
                    'cost_price' => $product['cost_price'],
                    'sum_cost_price' => $sum_cost_price,
                    'profit_price' => $profit_price,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                    'bom' => $bom
                ];

            }

            Db::startTrans();
            try {

                $info->save([
                    'vendors_id' => $params['vendors_id'] ?? 0,
                    'line_id' => $params['line_id'] ?? 0,
                    'dingdan_code' => $params['dingdan_code'],
                    'dingdan_date' => $params['dingdan_date'],
                    'product_type' => $params['product_type'],
                    'customer_id' => $params['customer_id'],
                    'delivery_date' => $params['delivery_date'],
                    'technical_requirements' => $params['technical_requirements'] ?? '',
                    'design_drawings' => $params['design_drawings'] ?? '',
                    'remarks' => $params['remarks'] ?? '',
                    'price' => $order_price,
                    'amount' => $order_price,
                    'cost_amount' => $cost_amount,
                    'profit_amount' => PreciseCalculator::sub($order_price, $cost_amount),
                    'dingdan_status' => self::STATUS_WAIT,
                ]);

                OrderProductModel::where('dingdan_id', $info['id'])->delete();
                OrderBomModel::where('dingdan_id', $info['id'])->delete();

                foreach ($productOrder as $productItem) {
                    $productItem['dingdan_id'] = $info['id'];
                    $bom = $productItem['bom'];
                    unset($productItem['bom']);
                    $dingdan_product_id = OrderProductModel::insertGetId($productItem);
                    foreach ($bom as $bomItem) {
                        $bomItem['dingdan_id'] = $info['id'];
                        $bomItem['dingdan_product_id'] = $dingdan_product_id;
                        OrderBomModel::insert($bomItem);
                    }
                }


                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->error = $exception->getMessage();
                return false;
            }

        }


        return true;
    }


    /**
     * Notes: 订单详情
     * User: chenLei
     * Date: 9/9/25
     * @param $params
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        $info = $info->toArray();
        $info['customer'] = CustomerModel::where('id', $info['customer_id'])->field('id,customer_name,phone1')
            ->find();

        $info['bom'] = OrderBomModel::where('dingdan_id', $info['id'])->select()->toArray();
        $info['product'] = OrderProductModel::where('dingdan_id', $info['id'])->select()->toArray();
        $info['sales_person'] = UserModel::where('id', $info['user_id'])->value('realname');

        $info['line'] = LineModel::where('id', $info['line_id'])->find();
        $info['vendors'] = VendorsModel::where('id', $info['vendors_id'])->find();

        return $info;

    }


    /**
     * Notes: 发起订单审批
     * User: chenLei
     * Date: 9/11/25
     * @param $params
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initiateApproval($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if (!in_array($info->dingdan_status, [self::STATUS_WAIT, self::STATUS_FAIL])) {
            $this->error = '该状态不能发起审批';
            return false;
        }

        $approvalModel = new ApprovalModel();
        $list = $approvalModel->where('type', $info->product_type)->order('weigh')->select();
        if (empty($list) || count($list) <= 0) {
            $this->error = '该审批节点还未配置，请先配置';
            return false;
        }

        $date = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            $info->dingdan_status = self::STATUS_ING;
            $info->approval_user_id = $params['login_user_id'];
            $info->approval_time = $date;
            $info->save();

            $code = 'SP' . time() . rand(100000, 999999);
            $orderApprovalModel = new OrderApprovalModel();
            $orderApprovalId = $orderApprovalModel->insertGetId([
                'user_id' => $params['login_user_id'],
                'dingdan_id' => $info['id'],
                'code' => $code,
                'status' => OrderApprovalModel::STATUS_ING,
                'create_time' => $date,
                'update_time' => $date,
            ]);


            $approval_user_list = [];

            foreach ($list as $key => $item) {
                if ($key == 0) {
                    $status = self::STATUS_ING;
                } else {
                    $status = self::STATUS_WAIT;
                }

                $approval_user_list[] = [
                    'dingdan_id' => $info['id'],
                    'dingdan_approval_id' => $orderApprovalId,
                    'department_id' => $item['department_id'],
                    'user_id' => $item['user_id'],
                    'status' => $status,
                    'create_time' => $date,
                    'update_time' => $date,
                ];
            }

            $orderApprovalUserModel = new OrderApprovalUserModel();
            $orderApprovalUserModel->insertAll($approval_user_list);

            $orderLog = new OrderLogModel();
            $orderLog->save([
                'dingdan_id' => $info['id'],
                'dingdan_approval_id' => $orderApprovalId,
                'department_id' => 2,
                'user_id' => $params['login_user_id'],
                'remark' => '发起审批',
                'status' => OrderLogModel::INITIATE_APPROVAL,
            ]);

            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

    }


    /**
     * Notes: 撤销审批
     * User: chenLei
     * Date: 9/11/25
     * @param $params
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancel($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if (!in_array($info->dingdan_status, [self::STATUS_ING])) {
            $this->error = '该状态不能撤销审批';
            return false;
        }

        $approvalUser = new OrderApprovalUserModel();
        $list = $approvalUser->where('dingdan_id', $params['id'])->select();

        foreach ($list as $item) {
            if ($item['op_time'] != null) {
                $this->error = '该订单已经有人审批暂时无法查看';
                return false;
            }
        }

        Db::startTrans();
        try {
            $info->dingdan_status = self::STATUS_WAIT;
            $info->save();

            $orderApprovalModel = new OrderApprovalModel();
            $orderLog = new OrderLogModel();
            $orderLog->save([
                'dingdan_id' => $info['id'],
                'dingdan_approval_id' => $orderApprovalModel->where('dingdan_id', $params['id'])->value('id'),
                'user_id' => $params['login_user_id'],
                'department_id' => 2,
                'remark' => '撤销审批',
                'status' => OrderLogModel::REVOKE,
            ]);


            $orderApprovalModel->where('dingdan_id', $params['id'])->delete();

            $orderApprovalUserModel = new OrderApprovalUserModel();
            $orderApprovalUserModel->where('dingdan_id', $params['id'])->delete();


            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }
    }


    /**
     * Notes: 技术修改图纸
     * User: chenLei
     * Date: 9/15/25
     * @param $params
     * @return bool
     */
    public function updateTechnicalRequirements($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }


        $info->technical_requirements = $params['technical_requirements'] ?? '';
        $info->design_drawings = $params['design_drawings'] ?? '';
        $info->save();

        return true;

    }


    /**
     * Notes: 仓库确认领料
     * User: chenLei
     * Date: 10/27/25 10:54:55
     * @param $params
     * @return bool
     */
    public function receivedMaterials($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->product_type != self::TYPE_BZ) {
            $this->error = '非生产类型订单，请勿操作';
            return false;
        }

        if ($info->dingdan_status != self::STATUS_WAITING_MATERIAL) {
            $this->error = '订单状态不等于待领料状态，请勿操作';
            return false;
        }

        $info->dingdan_status = self::STATUS_MATERIAL_RECEIVED_IN_PRODUCTION;
        $info->receive_material_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }

    /**
     * Notes: 生产完成
     * User: chenLei
     * Date: 10/27/25 11:31:32
     * @param $params
     * @return bool
     */
    public function productionComplete($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if ($info->product_type != self::TYPE_BZ) {
            $this->error = '非生产类型订单，请勿操作';
            return false;
        }

        if ($info->dingdan_status != self::STATUS_MATERIAL_RECEIVED_IN_PRODUCTION) {
            $this->error = '订单状态不等于 已领料生产中，请勿操作';
            return false;
        }

        $info->dingdan_status = self::STATUS_PRODUCTION_COMPLETED;
        $info->production_complete_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }


    /**
     * Notes: 生产完成入库
     * User: chenLei
     * Date: 10/27/25 11:40:41
     * @param $params
     * @return false|void
     */
    public function productionCompletedInbound($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if ($info->product_type != self::TYPE_BZ) {
            $this->error = '非生产类型订单，请勿操作';
            return false;
        }

        if ($info->dingdan_status != self::STATUS_PRODUCTION_COMPLETED) {
            $this->error = '订单状态不等于 生产完成，请勿操作';
            return false;
        }

        $info->dingdan_status = self::STATUS_WAREHOUSED;
        $info->warehousing_time = date('Y-m-d H:i:s');
        $info->save();
    }


    /**
     * Notes: 销售确认交付
     * User: chenLei
     * Date: 10/27/25 11:55:53
     * @param $params
     * @return false|void
     */
    public function confirmProductionCompleted($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }

        if ($info->product_type != self::TYPE_BZ) {
            if ($info->dingdan_status != self::STATUS_WAREHOUSED) {
                $this->error = '订单状态不等于 生产完成，请勿操作';
                return false;
            }
        } else {
            if ($info->dingdan_status != self::STATUS_SUCCESS) {
                $this->error = '订单状态还没到审批结束，请勿操作';
                return false;
            }
        }


        $info->dingdan_status = self::STATUS_DELIVERY_CONFIRMED;
        $info->delivery_time = date('Y-m-d H:i:s');
        $info->save();

    }


    /**
     * Notes: 外协确认开始生产
     * User: chenLei
     * Date: 11/3/25 14:23:15
     * @param $params
     * @return bool
     */
    public function submitProductionExecution($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->dingdan_status != self::STATUS_WAITING_MATERIAL) {
            $this->error = '订单状态不等于待生产，请勿操作';
            return false;
        }
        $info->dingdan_status = self::STATUS_OUTSOURCING_IN_PRODUCTION;
        $info->start_production_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }


    /**
     * Notes: 外协生产完成
     * User: chenLei
     * Date: 11/3/25 14:24:57
     * @param $params
     * @return bool
     */
    public function productionCompleted($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->dingdan_status != self::STATUS_OUTSOURCING_IN_PRODUCTION) {
            $this->error = '订单状态不等于生产中，请勿操作';
            return false;
        }
        $info->dingdan_status = self::STATUS_OUTSOURCING_COMPLETED;
        $info->outsourcing_completed_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }


    /**
     * Notes: 外协确认交付
     * User: chenLei
     * Date: 11/3/25 14:27:44
     * @param $params
     * @return bool
     */
    public function wxConfirmDelivery($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->dingdan_status != self::STATUS_OUTSOURCING_COMPLETED) {
            $this->error = '订单状态不等于生产完成，请勿操作';
            return false;
        }
        $info->dingdan_status = self::STATUS_DELIVERY_CONFIRMED;
        $info->delivery_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }
}